package com.phoenix.jsef.security.browser;

import com.phoenix.jsef.basedata.pojo.CBaseUserEntity;
import com.phoenix.jsef.basedata.pojo.CBaseUserTags;
import com.phoenix.jsef.basedata.shared.IBizBaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version V1.0
 * @ClassName: UserDetailsServiceImpl
 * @Description:TODO()
 * @author: 李启联
 * @date: 2019-08-16 09:46
 * @Copyright: Copyright (c), 2018-2019
 * 申明：本内容未经作者本人同意,禁止外泄以及用于其他的商业项目.
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IBizBaseUser userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        CBaseUserEntity user = null;
        try {
           user = userService.findBaseUserByFieldName(CBaseUserTags.Account,username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }

        Set<String> permissions = null;
        try {
            permissions = userService.findPermissions(user.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<GrantedAuthority> grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
        return new JwtUserDetails(user.getName(), user.getPassword(), user.getSalt(), grantedAuthorities);
    }
}